package com.eascs.paymentdetail.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.demand.service.DemandService;
import com.eascs.paymentdetail.dao.O2oPaymentDetailDao;
import com.eascs.paymentdetail.entity.O2oTransferAccount;
import com.eascs.paymentdetail.vo.O2oTransferAccountVo;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.Date;

/**
 * @ClassName: O2oTransferAccountService
 * @Description: 付款转账服务实现
 * @author 张庆奇
 * @date 2017年5月16日 下午2:50:54
 * @version V1.0
 */
@Service
public class O2oTransferAccountService {
	@Reference
	SysOrgService sysOrgService;
	@Autowired
	O2oPaymentDetailDao paymentDetailDao;
	@Value("${o2o.admin.service}")
	String url;
	@Inject
	private DemandService demandService;
	@Reference
	private WorkFlowService workFlowService;

	private static Logger log = LoggerFactory.getLogger(O2oTransferAccountService.class);

	/**
	 * @Title: findByPage
	 * @Description: 查询付款转账信息
	 * @author 张庆奇
	 * @param vo
	 * @return
	 * @return PageResult<Object[]>
	 * @throws @date
	 *             2017年5月16日 下午2:53:18
	 */
	public PageResult<Object[]> findByPage(O2oTransferAccountVo vo) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, vo.getPageSize(), vo.getPageIndex());
		StringBuffer querySql = new StringBuffer();

		// 导出excel语句
		if (StringUtil.isEmpty(vo.getFlag())) {
			querySql.append(" select id,bill_code,collection_user_name,pay_amount,collection_account,");
		} else {
			querySql.append(" select bill_code,collection_user_name,pay_amount,collection_account,");
		}

		querySql.append(" collection_bank_name,collection_bank_address,transfer.creator as creator,creat_date,item_name as bill_status");
		querySql.append(" FROM o2o_transfer_accounts transfer LEFT JOIN ");
		querySql.append(
				" pub_dditem_o2o item ON transfer.bill_status = item.item_code AND dd_no = 8942 AND item.is_lock = 'N'");
		querySql.append("  WHERE /**DATA_PERMISSION(transfer.LTD)**/ 1=1 and  transfer.is_del='N' ");
		if (!StringUtil.isEmpty(vo.getBillCode())) {
			querySql.append(" AND transfer.BILL_CODE LIKE ? ");
			sqlPageQuery.addLikeParam(vo.getBillCode());
		}

		if (!StringUtil.isEmpty(vo.getCollectionUserName())) {
			querySql.append(" AND transfer.collection_user_name LIKE ? ");
			sqlPageQuery.addLikeParam(vo.getCollectionUserName());
		}
		if (!StringUtil.isEmpty(vo.getBillStatus())) {
			querySql.append(" AND transfer.bill_status = ? ");
			sqlPageQuery.addParam(vo.getBillStatus());
		}

		if (!StringUtil.isEmpty(vo.getStartDate())) {
			querySql.append(" AND transfer.creat_date >= ? ");
			sqlPageQuery.addParam(vo.getStartDate());
		}
		if (!StringUtil.isEmpty(vo.getEndDate())) {
			querySql.append(" AND transfer.creat_date < date_add(?, INTERVAL 1 DAY) ");
			sqlPageQuery.addParam(vo.getEndDate());
		}

		querySql.append(" ORDER BY transfer.creat_date DESC ");
		sqlPageQuery.setQuerySql(querySql.toString());
		return paymentDetailDao.findDataWithPage(sqlPageQuery);
	}

	@Transactional(transactionManager = "o2oTransactionManager")
	public int save(O2oTransferAccount vo) {
		User user = UserHolder.getUser();
		vo.setCreatDate(new Date());
		vo.setCreatId(user.getNo());
		vo.setCreator(user.getCname());
		vo.setIsDel(StatusContexts.O2O_NO);
		vo.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
		return paymentDetailDao.insert(vo);
	}

	public O2oTransferAccount findById(String id) {
		return paymentDetailDao.getById(O2oTransferAccount.class, id);
	}

	public boolean isHaveRUNTransferAccountFlow(String id) {
		StringBuffer sql = new StringBuffer(
				"select count(1) from o2o_transfer_accounts where (bill_status='NEW' or bill_status='BH') and 1=1 ");
		if (StringUtil.isNotBlank(id)) {
			sql.append(" and id =  '" + id + "'");
		}
		int count = paymentDetailDao.findInteger(sql.toString());
		if (count > 0) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * @Title: startPayFlow
	 * @Description: 发起付款转账流程
	 * @author 张庆奇
	 * @param o2oTransferAccount
	 * @return
	 * @return ModelResult<Boolean>
	 * @throws @date
	 *             2017年5月18日 下午3:14:11
	 */
	public ModelResult<Boolean> startPayFlow(O2oTransferAccount o2oTransferAccount) { // 根据单号去启动流程
		O2oTransferAccount vo = findById(o2oTransferAccount.getId());
		User user = UserHolder.getUser();

		WFRequestParam param = new WFRequestParam();
		param.setReferId(vo.getId());
		param.setReferCode(vo.getBillCode());
		param.setReferUrl(url + "/transferAccountsRest/pay_approval");
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(ProcessTemplate.PROECESS_TYPE_FKZZ);
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
//		String ltd = demandService.getLtdByUserNo(user.getNo());
		ModelResult<ActOrgEntity> modelResult1 = sysOrgService.getUniquePlatformWithUser(user.getNo());
		if (!modelResult1.isSuccess()) {
			log.info("款转账流程错误{}", modelResult1.getErrMsg());
			ModelResult<Boolean> modelResult2 =new ModelResult<Boolean>();
			modelResult2.withError(modelResult1.getErrMsg(), modelResult1.getErrMsg());
			return modelResult2;
		}
		String ltd=modelResult1.getModel().getUnitNo();
		param.setOrgNo(ltd);

		log.info("提交人：【{}，{},{}】", user.getNo(), user.getCname(), ltd);

		StringBuffer appliedDes = new StringBuffer("收款人:");
		appliedDes.append(o2oTransferAccount.getCollectionUserName());
		appliedDes.append("，付款金额:");
		java.text.DecimalFormat df = new java.text.DecimalFormat("0.00"); // 格式化，保留两位小数
		appliedDes.append(df.format(o2oTransferAccount.getPayAmount().doubleValue()));
		param.setAppliedDes(appliedDes.toString());
		log.info("启动付款转账流程，参数id：【{}】，单据号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", o2oTransferAccount.getId(),
				o2oTransferAccount.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), ltd,
				appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		return modelResult;
	}

	public int updateEntityById(O2oTransferAccount o2oTransferAccount) {
		return paymentDetailDao.updateById(o2oTransferAccount);
	}

}
